import { ref, reactive } from 'vue'
import { request } from '@/common/sju.request.js'

const defaultConfig = {
    pageIndex: 1,
    pageSize: 10,
    data: {},
    autoLoad: true,
    showToast: true
}

const useList = (url, method = 'get', config = {}) => {
    const {
        pageIndex,
        pageSize,
        data,
        autoLoad,
        showToast
    } = { ...defaultConfig, ...config }

    const list = ref([])
    const loading = ref(false)
    const finished = ref(false)
    const error = ref(null)

    const pageInfo = reactive({
        pageIndex,
        pageSize,
        total: 0
    })

    const getList = async (reset = false) => {
        if (loading.value) return
        
        loading.value = true
        error.value = null

        try {
            if (reset) {
                pageInfo.pageIndex = defaultConfig.pageIndex
                finished.value = false
            }

            const params = {
                ...pageInfo,
                ...data
            }

            const res = await request(url, method, params)
            
            if (pageInfo.pageIndex === 1) {
                list.value = res.data.list || []
            } else {
                list.value = [...list.value, ...(res.data.list || [])]
            }

            pageInfo.total = res.data.total || 0
            pageInfo.pageIndex += 1
            finished.value = !res.data.list || res.data.list.length < pageInfo.pageSize

            return res
        } catch (err) {
            error.value = err
            throw err
        } finally {
            loading.value = false
            uni.stopPullDownRefresh()
        }
    }

    const getMoreList = async () => {
        if (finished.value || loading.value) return
        
        const res = await getList()
        if (showToast && (!res.data.list || res.data.list.length === 0)) {
            uni.showToast({
                title: '已经加载全部',
                icon: 'none'
            })
        }
    }

    const init = () => getList(true)

    if (autoLoad) {
        init()
    }

    onPullDownRefresh(init)
    onReachBottom(getMoreList)

    return {
        list,
        loading,
        finished,
        error,
        pageInfo,
        getList,
        getMoreList,
        init
    }
}

export { useList }
